package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint({ "HandlerLeak", "NewApi", "DefaultLocale" })
public class StoScanLoadingSendPieceActivity extends StoListenerActivity {

	private StoHhmEditText carCode;
	private StoHhmEditText nextStation;
	// private StoHhmEditText barCode;
	private DataBusinessEntity dataBusiness;
	private String nextStationCode = "", nextStationName = "";
	private final int DESTINATION_RESULT = 0xfd;
	private String busiType = HomeBroadAction.SCANNER_MAN_BROAD;
	// 下一站ID必须是6位
	// private int NEXT_STATION_LENGTH = 6;
	private List<EditText> edit = new ArrayList<EditText>();

	// 手动结果
	protected static final int HAND_RESULT = 0x4f;

	private TextView weight;
	private float blueWeight = -1;
	private String billNo="";
	private BaseDialog filterDialog=null;

	@SuppressLint("DefaultLocale")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == HAND_RESULT) {
				if (CheckItemData(msg.obj.toString(), HAND_RESULT)) {
					processScanData();
					code.requestFocus();
				}
				code.setText("");
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_loading_send_piece);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.loadcar_send_piece, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE);
		}

		bluetoothConnect();

	}

	private void initWidget() {
		carCode = (StoHhmEditText) this.findViewById(R.id.car_seal);
		nextStation = (StoHhmEditText) this.findViewById(R.id.nextStation);

		code = (StoHhmEditText) this.findViewById(R.id.center_code);
		weight = (TextView) this.findViewById(R.id.enter_count);
		// ticketNumber = (TextView)
		// this.findViewById(R.id.nophone_tickets_text);
		// carCode.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

		// carCode.setInputType(InputType.TYPE_CLASS_TEXT);
		edit.add(carCode);
		edit.add(nextStation);
		edit.add(code);
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_SCANNING_SENDPIECE);

			addUploadTable(EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE);

		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_SENDPIECE);

			addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE);

		}
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (!weight.getText().toString().isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				return;
			}

			if (!code.getText().toString().isEmpty()) {

				billNo=code.getText().toString();

				float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();
				if(blueWeight>maxWeight){
					ScanOff();
					filterDialog=new BaseDialog(this);
					filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
					filterDialog.show();
					filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							//Add by wj过滤单号
							boolean isFilter= BillFilterUtil.isFilter(billNo,StoScanLoadingSendPieceActivity.this);
							if(isFilter){
								showFilterDialog(code.getText().toString().trim());
								return;
							}
							//End by wj
							if (addPieceRecord(billNo)) {
								setSaveData(true);
								// SoundManager.getInstance(this).playSuccessSound();
								Helper.showSoundAndVibrator(StoScanLoadingSendPieceActivity.this, true);
								addScanRecordInfo(billNo,weight.getText().toString());
								// ticketNumber.setText(String.valueOf(++count));
								// barcode.setSelection(barcode.length());

							}
							// 提示插入数据失败
							else {
								Helper.showSoundToast(StoScanLoadingSendPieceActivity.this,
										getString(R.string.code_repeat), false);
							}
							ScanOpen();
						}
					});
				}else {
					//Add by wj过滤单号
					boolean isFilter= BillFilterUtil.isFilter(billNo,this);
					if(isFilter){
						showFilterDialog(billNo);
						return;
					}
					//End by wj

					if (addPieceRecord(billNo)) {
						setSaveData(true);
						// SoundManager.getInstance(this).playSuccessSound();
						Helper.showSoundAndVibrator(this, true);
						addScanRecordInfo(billNo);
						// ticketNumber.setText(String.valueOf(++count));
						// barcode.setSelection(barcode.length());

					}
					// 提示插入数据失败
					else {
						Helper.showSoundToast(this,
								getString(R.string.code_repeat), false);
					}
					ScanOpen();
				}

			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord(String billNo) {
		boolean ret = false;

		// 铅封号
		dataBusiness.setBag_number(carCode.getText().toString());

		// 下一站
		dataBusiness.setNext_station(nextStationCode);
		// 下一站名称
		dataBusiness.setUser_defined3(nextStation.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());

		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}

		// dataBusiness.setDifferent_flag(ScanTypeEntity.TYPE_SCAN_UPCAR);

		insertLeadSealingOperate(carCode.getText().toString());

		ret = insertLoadCarSendpiece(billNo);
		/*
		 * if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) { // 扫描类型
		 * dataBusiness.setCommand_type(EnumTableNames.
		 * STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE.getOpCode()); // 插入铅封操作
		 * dataBusiness.setBar_code_number(carCode.getText().toString());
		 * 
		 * dataBusiness.setCodeType(getExpType(carCode.getText().toString()));
		 * ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
		 * EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE); if (ret)
		 * {
		 * addUploadTable(EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE
		 * ); this.addCodeNumber(); } dataBusiness.setDifferent_flag(""); //
		 * 扫描类型 dataBusiness.setCommand_type(EnumTableNames.
		 * STATUS_TABLE_LOADCAR_SENDPIECE.getOpCode()); // 单号
		 * dataBusiness.setBar_code_number(code.getText().toString()); // 单号类型
		 * dataBusiness.setCodeType(getExpType(code.getText().toString())); //
		 * 插入装车发件 ret =
		 * StoDataBaseOperation.getInstance(this).insert(dataBusiness,
		 * EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE); if (ret) {
		 * addUploadTable(EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE);
		 * this.addCodeNumber(); }
		 * 
		 * } else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) { // 插入铅封操作
		 * dataBusiness.setBar_code_number(carCode.getText().toString()); //
		 * 单号类型
		 * dataBusiness.setCodeType(getExpType(carCode.getText().toString()));
		 * // 扫描类型 dataBusiness.setCommand_type(EnumTableNames.
		 * STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE.getOpCode());
		 * 
		 * ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
		 * EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE); if (ret) {
		 * addUploadTable
		 * (EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE);
		 * this.addCodeNumber(); } dataBusiness.setDifferent_flag(""); // 单号
		 * dataBusiness.setBar_code_number(code.getText().toString()); // 单号类型
		 * dataBusiness.setCodeType(getExpType(code.getText().toString())); //
		 * 扫描类型 dataBusiness.setCommand_type(EnumTableNames.
		 * STATUS_TABLE_CENTER_LOADCAR_SENDPIECE.getOpCode()); // 插入装车发件 ret =
		 * StoDataBaseOperation.getInstance(this).insert(dataBusiness,
		 * EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE); if (ret) {
		 * addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE);
		 * this.addCodeNumber(); } }
		 */

		return ret;
	}

	/**
	 * 插入装车发件
	 * 
	 * @param code
	 *            运单号
	 * @return
	 */
	private boolean insertLoadCarSendpiece(String code) {
		boolean ret = false;
		// 单号
		dataBusiness.setBar_code_number(code);
		// 单号类型
		dataBusiness.setCodeType(getExpType(code));

		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE
							.getOpCode());
			// 插入装车发件
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE);
			if (ret) {
				addUploadTable(EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE);
				this.addCodeNumber();
			}
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE
							.getOpCode());
			// 插入装车发件
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE);
			if (ret) {
				addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE);
				this.addCodeNumber();
			}
		}

		return ret;
	}

	/**
	 * 插入铅封数据
	 * 
	 * @param code
	 *            铅封号
	 * @return
	 */
	private boolean insertLeadSealingOperate(String code) {
		boolean ret = false;

		// 单号
		dataBusiness.setBar_code_number(code);
		// 单号类型
		dataBusiness.setCodeType(getExpType(code));

		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE
							.getOpCode());
			// 插入铅封操作
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE);
			if (ret) {
				addUploadTable(EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE);
				this.addCodeNumber();
			}
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE
							.getOpCode());
			// 插入铅封操作
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE);
			if (ret) {
				addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE);
				this.addCodeNumber();
			}
		}

		return ret;
	}

	/**
	 * 监听控件
	 */
	private void initListen() {

	

		carCode.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				if (carCode.getText().toString().length() == 0) {
					Helper.showSoundToast(StoScanLoadingSendPieceActivity.this,
							"铅封条码不能为空!", false);
					carCode.setText("");
					return;
				}
				if (ScanRuleManager.getInstance(
						StoScanLoadingSendPieceActivity.this).isCarSealCode(
						carCode.getText().toString())) {
					nextStation.requestFocus();
					nextStation.setSelection(nextStation.getText().toString()
							.length());
					return;

				} else {
					// 错误铅封条码
					Helper.showSoundToast(StoScanLoadingSendPieceActivity.this,
							"非申通铅封条码!", false);
					carCode.setText("");
					return;
				}

			}
		});

		nextStation.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				carCode.requestFocus();
				// carCode.setSelection(carCode.getText().toString().length());
			}

			@Override
			public void onEditClickListener(View v) {
//				selectNextStation();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectNextStation();
			}
		});

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				nextStation.requestFocus();
				// nextStation.setSelection(nextStation.getText().toString()
				// .length());
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
				/*
				 * if (code.getText().toString().length() == 0) {
				 * Helper.showSoundToast(StoScanLoadingSendPieceActivity.this,
				 * getString(R.string.code_empty), false); } else { Message msg
				 * = handler.obtainMessage(); msg.what = HAND_RESULT; msg.obj =
				 * code.getText().toString(); handler.sendMessage(msg); }
				 */

			}
		});
		/*
		 * barCode.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) { Message msg =
		 * handler.obtainMessage(); msg.what = HAND_RESULT; msg.obj =
		 * barCode.getText().toString(); handler.sendMessage(msg); } });
		 */
		/*
		 * barCode.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		for (EditText editListener : edit) {

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					if (nextStation.getText().toString().isEmpty()) {
						nextStationCode = "";
						nextStationName = "";
					}
					if (carCode.getText().toString().trim().length() == 9
							&& Helper.isNumeric(carCode.getText().toString()
									.trim())) {
						carCode.setText("STO"
								+ carCode.getText().toString().trim());
						carCode.setSelection(12);
						// code.selectAll();
					} else if (carCode.getText().toString().trim().length() == 12) {

					} else if (carCode.getText().toString().trim().length() == 0) {

					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
	}

	/**
	 * 单号逻辑处理判断
	 * 
	 * @author wxf
	 * 
	 */
	private void codeProcess() {
		String codeName = code.getText().toString();

		GetTableParcel data;
		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			if (codeName.length() == NEXT_STATION_LENGTH) {
				data = queryNextStation(codeName);
				if (data != null) {
					nextStation.setText(data.getSelectName());
					nextStationCode = data.getSelectCode();
					nextStationName = data.getSelectName();
				} else {
					nextStationName = "";
					Helper.showSoundToast(this, getString(R.string.undefined),
							false);
				}
				code.setText("");

			} else if (codeName.length() == CAR_CODE_LENGTH) {
				carCode.setText("STO" + codeName);
				code.setText("");
			} else {
				Message msg = handler.obtainMessage();
				msg.what = HAND_RESULT;
				msg.obj = code.getText().toString();
				handler.sendMessage(msg);
			}
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param
	 *
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String barcode, EnumTableNames type) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(barcode, type);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(
			// this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 非法铅封条码
		case CAR_SEAL_ILLEGAL:
			Helper.showSoundToast(this, "非法铅封条码", false);
			break;
		// 铅封条码
		case CODE_SEAL_OK:
			// 铅封号
			carCode.setText(barcode);
			nextStation.requestFocus();
			ret = true;
			break;
		// 成功条码
		case CODE_WAY_BILL:
			// System.out.println(barcode + "!!@@@!");
			if (type == null) {
				code.setText(barcode);
				code.setSelection(code.length());
			}
			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 检查数据是否合法
	 * 
	 * @return boolean
	 */
	@SuppressLint("NewApi")
	private boolean CheckItemData(String barcode, int handleType) {
		boolean ret = false;
		if (handleType == HAND_RESULT) {
			// 检查单号
			if (!CheckScanCode(barcode, null)) {
				code.setText("");
				code.requestFocus();
				return ret;
			}
		}
		if (carCode.getText().toString().length() == 0) {
			Helper.showSoundToast(this, "铅封条码不能为空!", false);
			carCode.setText("");
			carCode.requestFocus();
			return ret;
		}

		/*
		 * if((!carCode.getText().toString().substring(0,
		 * 3).equals(ProcessScanCode.sto)) ||
		 * (!carCode.getText().toString().substring(0,
		 * 3).equals(ProcessScanCode.STO)) ){ Helper.showSoundToast(this,
		 * "非申通铅封条码!", false); carCode.setText(""); carCode.requestFocus();
		 * return ret; }
		 */
		// 检查铅封条码
		if (!CheckScanCode(carCode.getText().toString(),
				EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE)) {
			carCode.setText("");
			carCode.requestFocus();
			return ret;
		}
		if (nextStation.getText().toString().length() == 0) {
			Helper.showSoundToast(this, "下一站不能为空!", false);
			nextStation.setText("");
			nextStation.requestFocus();
			return ret;
		}
		if (nextStationCode.isEmpty()) {
			Helper.showSoundToast(this, "下一站不能为空!", false);
			nextStation.setText("");
			nextStation.requestFocus();
			return ret;
		}
		if (!nextStationName.equals(nextStation.getText().toString())) {
			Helper.showSoundToast(this, "请选择正确的下一站!", false);
			nextStation.requestFocus();
			nextStation.setText("");
			return ret;
		}
		return true;
	}

	/**
	 * 选择下一站
	 */
	private void selectNextStation() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (nextStation.getText().toString().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ONLY_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ nextStation.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(SITE_CODE_NUMBER);
			tableParcel.setSelectName(SITE_CODE_NAME);
			tableParcel.setProperty(null);
			Intent intent = new Intent(this, StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, DESTINATION_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectNextStation", e.getMessage());
		}
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		// super.onBackPressed();
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == DESTINATION_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				nextStation.setText(courierEntity.getSelectName());
				nextStation.setSelection(nextStation.length());
				nextStationCode = courierEntity.getSelectCode();

				if (nextStationCode.length() > 0) {
					nextStationName = courierEntity.getSelectName();
					code.requestFocus();
				}
			}
		} else if (requestCode == DESTINATION_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			nextStation.setText("");
			nextStationName = "";
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		edit.clear();
		edit = null;
		handler.removeMessages(HAND_RESULT);
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;

			// 下一站编号
			if (result.length() == NEXT_STATION_LENGTH) {
				nextStation.setText(result);
				selectNextStation();
			} else {

				// 检查扫描的是铅封
				if (ScanRuleManager.getInstance(this).isCarSealCode(result)) {
					if (CheckScanCode(result,
							EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE)) {
						SoundManager.getInstance(
								StoScanLoadingSendPieceActivity.this)
								.playSuccessSound();
					}
				}
				// 如果扫到的是单号就做处理
				else {
					if (CheckScanCode(result,
							EnumTableNames.STATUS_TABLE_SCANNING_SENDPIECE)) {
						code.setText(result);
						code.setSelection(code.length());

						// System.out.println(result + "!!!!");
						if (CheckItemData(result, 0)) {
							processScanData();
							code.requestFocus();
						}
					}
					code.setText("");

				}
			}
		} else {

			// Helper.showSoundToast(StoScanLoadingSendPieceActivity.this,
			// "条码不能为空", false);
		}

	}

	/**
	 * 蓝牙连接
	 *
	 * @author wxf
	 *
	 */
	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				// weight.setText(R.string.blue_no_open);
			}
		} else {
			// promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	/**
	 * 蓝牙正式连接
	 */
	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
			// weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this, bluetoothHandler,
					macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if (blueConnCount < 3) {
								blueConnecting();
								blueConnCount++;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",正在重连" + blueConnCount + "...");
							} else {
								blueConnCount = 0;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(getText(
									R.string.no_select_scales_model).toString()
									+ "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};

}
